<?php

namespace App\Http\Controllers\Auth;

use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Db;
use Illuminate\Support\Facades\Session;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use App\Services\SmsService;
use App\User;
use App\Services\UCenterService;

class LoginController extends Controller
{
    /*
    |--------------------------------------------------------------------------
    | Login Controller
    |--------------------------------------------------------------------------
    |
    | This controller handles authenticating users for the application and
    | redirecting them to your home screen. The controller uses a trait
    | to conveniently provide its functionality to your applications.
    |
    */
    // use AuthenticatesUsers;

    /**
     * Where to redirect users after login.
     *
     * @var string
     */
    protected $redirectTo = '/';

    /**
     * Create a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('guest')->except('logout');
    }

    public function showLoginForm()
    {
        return view("auth.login");
    }

    /**
     * login 【用户名密码登录】
     *
     * @param  Request $request
     *
     * @return [type]
     */
    public function login(Request $request)
    {
      // $id = Session::get('id');
      //
      // $data = $request->all();
      // //dd($data['captcha']);
      // $phone = Session::get('telphone');
      // $res = Session::get('captcha');
      // //dd($res);exit;
      // if($data['captcha'] == $res) {
      //   return redirect()->with('success','验证成功');
      // }else{
      //   return back()->with('error','验证失败');
      // }
        //实例话UC服务
        $client = new UCenterService();

        $mem['username'] = $request->input("name");
        $mem['password'] = MD5($request->input("password"));
        //请求UC服务器验证
        $UcenterObj = $client->sys_login($mem);
        $UCenterArray = json_decode($UcenterObj, true);//解析json用户信息数组，0=远程未注册
        $userinfo1=$client->getuserinfos($UCenterArray[0]);

       // dd($UCenterArray,$userinfo1);
        if ($UCenterArray) {

            //根据返回的sysid 查询本地数据
            //$results=DB::table('users')->where(['sysid'=>$UCenterArray[0],'name'=>$request->input("name"),'password'=>bcrypt($request->input("password"))])->get();


            if (!Auth::attempt(['sysid' => $UCenterArray[0], 'name' => $request->input("name"), 'password' => $request->input("password")])) {
                $userinfo=$client->getuserinfos($UCenterArray[0]);
                $userArray = [
                    'sysid' => $UCenterArray[0],
                    'telphone' => $userinfo['cellphone'],
                    'email' => $userinfo['email'] ? $userinfo['email'] : 'uc@ma.cn',
                    'name' => $request->input("name"),
                    'password' => bcrypt($request->input("password"))
                ];
                //本地注册账号
                User::create($userArray);
                //重新授权登陆
                Auth::attempt(['sysid' => $UCenterArray[0], 'name' => $request->input("name"),'password' => $request->input("password")]);
            }
//            else {
                //$request->session()->flash('status', '登陆失败!');
//            }
            return redirect($this->redirectTo);
        } else {//远程未注册，打印提示信息

            $request->session()->flash('status', '用户不存在，请先注册账号！');
        }

        return view("auth.login");
    }
    /**
     * [sms 发送短信]
     * @return [type] [发送短信]
     */
    public function sendMsg()
    {
        $phone = 15029356918;
        $Verify = mt_rand(100000, 999999);

        $data = array((string)$Verify, '5');

        $rest = SmsService::sendSMS($phone, $data);
        if ($rest == null) {
            exit("发送失败!");
        }
        if ($rest->statusCode != 0) {
            exit("发送失败! 状态：" . $rest->statusCode);
        } else {
            exit("发送成功!");
        }
    }
    /**
     * 退出登录
     */
    public function logout(Request $request)
    {
        $this->guard()->logout();

        $request->session()->invalidate();

        return redirect('/');
    }

    /**
     * Get the guard to be used during authentication.
     *
     * @return \Illuminate\Contracts\Auth\StatefulGuard
     */
    protected function guard()
    {
        return Auth::guard();
    }

}
